var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/functionalComponent/antd/AsyncTree.tsx
var AsyncTree_exports = {};
__export(AsyncTree_exports, {
  AsyncTree: () => AsyncTree
});
module.exports = __toCommonJS(AsyncTree_exports);
var import_icons = require("@ant-design/icons");
var import_antd = require("antd");
var import_react = __toESM(require("react"));
var import_baseComponent = require("../../baseComponent");
var import_util = require("../../util");
var import_tree = require("./tree");
var filterTreeNode = (value, node, fieldNames = {}) => {
  var _a;
  const { title = "title", key = "key" } = fieldNames || {};
  const lowerCaseValue = (value == null ? void 0 : value.toLowerCase()) || "";
  const keyId = node[key];
  return ((_a = node[title]) == null ? void 0 : _a.toLowerCase().indexOf(lowerCaseValue)) > -1 || keyId === value;
};
function updateTreeData(nodes, key, children, nodeKey = "key") {
  let find = false;
  return nodes.map((node) => {
    if (node[nodeKey] === key) {
      find = true;
      return {
        ...node,
        ...children.length ? { children } : {
          isLeaf: true
        }
      };
    }
    if (!find && node.children) {
      return {
        ...node,
        children: updateTreeData(node.children, key, children, nodeKey)
      };
    }
    return node;
  });
}
function TreeRender({
  treeLoad,
  reader,
  onSelectedChange = void 0,
  onCheck,
  onSelect,
  lazyLoad,
  onSearch,
  defaultChange = false,
  ...props
}) {
  var _a, _b, _c;
  const data = reader().data;
  const treeRef = (0, import_react.useRef)({});
  const innerRef = (0, import_react.useRef)({ selectedKeys: "", activeKey: void 0 });
  const searchType = (0, import_react.useRef)({});
  const treeId = (0, import_react.useId)();
  const [{ data: state, key: treeKey }, setState] = (0, import_util.useRefState)({ data, key: treeId });
  const nodeKey = ((_a = props.fieldNames) == null ? void 0 : _a.key) || "key";
  const getState = (0, import_util.useRefCallback)(() => state);
  (0, import_react.useEffect)(() => {
    setState({ data });
  }, [data]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    if (innerRef.current && props.selectedKeys) {
      innerRef.current && (innerRef.current.selectedKeys = (_b2 = (_a2 = props.selectedKeys).join) == null ? void 0 : _b2.call(_a2, ","));
    }
  }, [props.selectedKeys]);
  (0, import_react.useEffect)(() => {
    if (treeRef.current && innerRef.current && props.checkedKeys) {
      innerRef.current.selectedKeys = props.checkedKeys.join(",");
      treeRef.current.selectNodes = props.checkedKeys.map((k) => getState().keyRef[k]);
    }
  }, [props.checkedKeys]);
  const [treeSelectCallback, onCheckCallback, onSelectCallback, onSearchCallback] = [
    (0, import_util.useRefCallback)((keys, { nodes, node }, type, dispatchChange = true) => {
      var _a2;
      if (!treeRef.current) {
        return;
      }
      const lastSelectedKeys = ((_a2 = innerRef.current) == null ? void 0 : _a2.selectedKeys) || "";
      innerRef.current.selectedKeys = keys.join(",");
      if (type === "selected") {
        treeRef.current.activeNode = node;
        innerRef.current.activeKey = node.key;
      }
      treeRef.current.selectNodes = nodes;
      treeRef.current.selectType = type;
      if (dispatchChange && innerRef.current.selectedKeys !== lastSelectedKeys) {
        onSelectedChange == null ? void 0 : onSelectedChange(keys, nodes, type);
      }
    }),
    (0, import_util.useRefCallback)((...args) => {
      treeSelectCallback(
        args[0].checked ? args[0].checked : args[0],
        {
          nodes: args[1].checkedNodes,
          node: args[1].node
        },
        "checked"
      );
      onCheck && onCheck(...args);
    }),
    (0, import_util.useRefCallback)((...args) => {
      treeSelectCallback(args[0], { nodes: args[1].selectedNodes, node: args[1].node }, "selected");
      onSelect && onSelect(...args);
    }),
    (0, import_util.useDebounce)(
      (value, includeChildren = false) => {
        searchType.current = { type: "search", value };
        const filterData = value ? import_util.iup.filterTree(data.nodes, (node) => filterTreeNode(value, node, props.fieldNames), { includeChildren }) : data.nodes;
        setState((p) => {
          return {
            key: `${treeId}_${value}`,
            data: {
              ...p.data,
              nodes: filterData
            }
          };
        });
      },
      { wait: 300 }
    )
  ];
  const onPropsSearch = (0, import_util.useRefCallback)((...args) => {
    onSearch == null ? void 0 : onSearch(...args);
    searchType.current.type = null;
  });
  (0, import_react.useEffect)(() => {
    if (searchType.current.type === "search" && state.nodes !== void 0) {
      onPropsSearch(searchType.current.value, state.nodes);
    }
  }, [state.nodes]);
  (0, import_util.useAsyncEffect)(async () => {
    if (state.nodes !== void 0) {
      await treeLoad(treeRef, getState, onSearchCallback, searchType);
    }
  }, [state.nodes]);
  const treeProps = props;
  const lastActiveKey = ((_b = innerRef.current) == null ? void 0 : _b.activeKey) ? [innerRef.current.activeKey] : void 0;
  if (props.checkable) {
    treeProps.selectable = props.selectable ?? false;
    treeProps.onCheck = onCheckCallback;
    treeProps.onSelect = (...args) => {
      treeRef.current.activeNode = args[1].node;
      innerRef.current.activeKey = args[1].node.key;
      onSelect && onSelect(...args);
    };
    treeProps.defaultCheckedKeys = props.defaultCheckedKeys || state.defaultCheckedKeys;
    if (treeProps.selectable) {
      treeProps.defaultSelectedKeys = lastActiveKey ?? (props.defaultSelectedKeys || state.defaultSelectedKeys);
    }
  } else {
    treeProps.onSelect = onSelectCallback;
    treeProps.defaultSelectedKeys = lastActiveKey ?? (props.defaultSelectedKeys || state.defaultSelectedKeys);
  }
  if (props.virtual === void 0) {
    treeProps.virtual = state._nodeCount_ > 60;
  }
  (0, import_util.useAsyncEffect)(async () => {
    const checkedKeys = state.defaultSelectedKeys;
    if (checkedKeys == null ? void 0 : checkedKeys.length) {
      treeSelectCallback(
        checkedKeys,
        { nodes: state.defaultSelectedNodes, node: state.firstNode },
        "selected",
        defaultChange
      );
    }
  }, [state.defaultSelectedKeys]);
  (0, import_util.useAsyncEffect)(async () => {
    const checkedKeys = state.defaultCheckedKeys;
    if (checkedKeys == null ? void 0 : checkedKeys.length) {
      treeSelectCallback(
        checkedKeys,
        {
          nodes: state.defaultCheckedNodes,
          node: state.defaultCheckedNodes[0]
        },
        "checked",
        defaultChange
      );
    }
  }, [state.defaultCheckedKeys]);
  const titleRender = (0, import_util.useRefCallback)((node) => {
    const oldRender = () => {
      var _a2, _b2;
      const title = props.checkable ? node[((_a2 = treeProps.fieldNames) == null ? void 0 : _a2.title) || "title"] : /* @__PURE__ */ import_react.default.createElement(
        import_antd.Dropdown,
        {
          disabled: !innerRef.current.selectedKeys.includes(node.key),
          trigger: ["contextMenu"],
          menu: { items: [{ key: "cancle", label: "取消选中" }] },
          placement: "top"
        },
        /* @__PURE__ */ import_react.default.createElement("span", null, node[((_b2 = treeProps.fieldNames) == null ? void 0 : _b2.title) || "title"])
      );
      return import_util.iup.isString(title) && searchType.current.value ? /* @__PURE__ */ import_react.default.createElement(import_util.HighlightText, { keyword: searchType.current.value, content: title }) : title;
    };
    if (treeProps.titleRender) {
      return treeProps.titleRender(node, oldRender);
    }
    return oldRender();
  });
  if (lazyLoad) {
    treeProps.loadData = async (parentNode) => {
      if (parentNode.children) {
        return;
      }
      const children = await lazyLoad(parentNode, getState().keyRef);
      setState((p) => {
        return {
          ...p,
          data: {
            ...p.data,
            nodes: updateTreeData(p.data.nodes, parentNode[nodeKey], children, nodeKey)
          }
        };
      });
    };
  }
  if ((_c = state.nodes) == null ? void 0 : _c.length) {
    const defaultExpandAll = searchType.current.type === "search" && searchType.current.value && !lazyLoad;
    if (treeProps.autoExpandParent && defaultExpandAll) {
      delete treeProps.autoExpandParent;
    }
    return /* @__PURE__ */ import_react.default.createElement(
      import_tree.Tree,
      {
        key: treeKey,
        directoryTree: true,
        defaultExpandedKeys: state.defaultExpandedKeys,
        defaultExpandAll,
        showIcon: true,
        ref: treeRef,
        ...treeProps,
        titleRender,
        treeData: state.nodes
      }
    );
  }
  return /* @__PURE__ */ import_react.default.createElement(import_antd.Empty, { image: import_antd.Empty.PRESENTED_IMAGE_SIMPLE });
}
function formatTreeNodes(parentNode, nodes, convertNode, extraParams, level = 0) {
  var _a;
  if (!nodes)
    return [];
  if (!convertNode) {
    convertNode = (n) => n;
  }
  const nodeKey = ((_a = extraParams.fieldNames) == null ? void 0 : _a.key) || "key";
  return nodes.map((data, index) => {
    var _a2;
    const depth = { level, index };
    const node = {
      depth,
      parentNode,
      key: data[nodeKey],
      ...convertNode(data, depth)
    };
    if (extraParams.initTreeData) {
      if (node[nodeKey] && node.isSelected) {
        extraParams.defaultSelectedKeys.push(node[nodeKey]);
        extraParams.defaultSelectedNodes.push(node);
        extraParams.firstNode = extraParams.firstNode || node;
        if ((parentNode == null ? void 0 : parentNode[nodeKey]) && !extraParams.defaultExpandedKeys.includes(parentNode[nodeKey])) {
          extraParams.defaultExpandedKeys.push(parentNode[nodeKey]);
        }
      }
      if (node[nodeKey] && node.isChecked) {
        extraParams.defaultCheckedKeys.push(node[nodeKey]);
        extraParams.defaultCheckedNodes.push(node);
      }
      extraParams._nodeCount_ += 1;
    }
    if (extraParams.lazyLoad) {
      if (data.children) {
        node.isLeaf = false;
        node.children = formatTreeNodes(node, data.children, convertNode, extraParams, depth.level + 1);
      }
    } else {
      node.isLeaf = !(data.children && data.children.length);
      if (!node.isLeaf) {
        node.children = formatTreeNodes(node, data.children, convertNode, extraParams, depth.level + 1);
      }
    }
    if ((_a2 = node.children) == null ? void 0 : _a2.length) {
      if (depth.level === 0 || node.expanded || extraParams.keyword) {
        extraParams.defaultExpandedKeys.push(node[nodeKey]);
      }
    }
    node[nodeKey] && (extraParams.keyRef[node[nodeKey]] = node);
    return node;
  });
}
async function getTreeInfo(props) {
  const { dataLoad, request, convertNode, lazyLoad, params, _isRefresh_ = false, fieldNames } = props;
  const transformData = dataLoad || ((n) => n);
  const extraParams = {
    lazyLoad,
    fieldNames,
    initTreeData: true,
    defaultExpandedKeys: [],
    defaultCheckedKeys: [],
    defaultCheckedNodes: [],
    defaultSelectedKeys: [],
    defaultSelectedNodes: [],
    firstNode: null,
    _nodeCount_: 0,
    keyRef: {}
  };
  try {
    let requestParams = params;
    if (import_util.iup.isFunction(params)) {
      requestParams = await params();
    }
    const nodes = await request({ ...requestParams }, _isRefresh_);
    return {
      nodes: transformData(formatTreeNodes(null, nodes, convertNode, extraParams), extraParams),
      ...extraParams
    };
  } catch {
    return {
      nodes: transformData([]),
      ...extraParams
    };
  }
}
var AsyncTree = (0, import_util.compHoc)(
  ({ onLoad, showFilter = true, style, filterOptions = {}, ...props }) => {
    const { params, dataLoad, request, convertNode, outRef, lazyLoad, loadData, treeData, virtual, ...others } = props;
    const loadRef = (0, import_react.useRef)({
      resolve: null,
      beforeLoad({ resolve }) {
        this.resolve = resolve;
      },
      onLoad() {
        if (this.resolve) {
          this.resolve(true);
          this.resolve = null;
        }
      }
    });
    const parameters = {
      ...props,
      dataLoad: (...args) => {
        loadRef.current.onLoad();
        return dataLoad ? dataLoad(...args) : args[0];
      }
    };
    const [dataReader, setDataReader] = (0, import_util.useAsyncSuspense)(getTreeInfo, parameters, request);
    const [search, setSearch] = (0, import_react.useState)({ type: "", value: "" });
    const lastParams = (0, import_react.useRef)(params);
    const updateParams = (0, import_util.useRefCallback)((newParam = {}, isRefresh = false) => {
      lastParams.current = { ...lastParams.current, ...newParam };
      setDataReader({
        ...parameters,
        params: import_util.iup.isFunction(newParam) ? newParam : lastParams.current,
        _isRefresh_: isRefresh
      });
    });
    const treeLoadCallback = (0, import_util.useRefCallback)((treeRef, getState, filter, searchType) => {
      var _a;
      outRef.current = {
        ...outRef.current,
        ...treeRef.current,
        searchType,
        filterTreeNode(value) {
          return filter(value, filterOptions == null ? void 0 : filterOptions.includeChildren);
        },
        refresh(newParam = {}, isRefresh = false) {
          return new Promise((resolve) => {
            loadRef.current.beforeLoad({ resolve });
            getState().nodes = void 0;
            updateParams(newParam, isRefresh);
          });
        },
        getSelectedNodes() {
          var _a2;
          return ((_a2 = treeRef.current) == null ? void 0 : _a2.selectNodes) || [];
        },
        getActiveNode() {
          var _a2;
          return (_a2 = treeRef.current) == null ? void 0 : _a2.activeNode;
        },
        getNodes() {
          return getState().nodes || [];
        },
        getSelectType() {
          var _a2;
          return (_a2 = treeRef.current) == null ? void 0 : _a2.selectType;
        },
        getNodeByKey(key) {
          return key ? getState().keyRef[key] : getState().keyRef;
        }
      };
      onLoad == null ? void 0 : onLoad(outRef.current, getState());
      (_a = outRef.current._compIns) == null ? void 0 : _a.getObserver().prevNotify({ ins: outRef.current }, "onLoad").then();
    });
    const debounceRefresh = (0, import_util.useDebounce)(
      (newParam, isRefresh) => {
        var _a, _b;
        (_b = (_a = outRef.current) == null ? void 0 : _a.refresh) == null ? void 0 : _b.call(_a, newParam, isRefresh);
      },
      { wait: 300, immediate: false }
    );
    const getRefresh = (debounce = false) => (newParam = {}, isRefresh = false) => {
      var _a, _b;
      if (debounce) {
        debounceRefresh(newParam, isRefresh);
      } else {
        (_b = (_a = outRef.current) == null ? void 0 : _a.refresh) == null ? void 0 : _b.call(_a, newParam, isRefresh);
      }
    };
    (0, import_react.useEffect)(() => {
      if (import_util.iup.isFunction(params) && lastParams.current !== params || import_util.iup.isObject(params) && !import_util.iup.isPropsEqual(lastParams.current, params, { shallow: true, exclude: ["keyword"] })) {
        getRefresh()(params);
      }
    }, [params]);
    (0, import_util.useIUPEffect)(
      () => {
        getRefresh()();
      },
      [request],
      false
    );
    (0, import_react.useEffect)(() => {
      var _a, _b, _c;
      if (search.type && ((_a = outRef.current) == null ? void 0 : _a.searchType)) {
        outRef.current.searchType.current = search;
        if (search.type === "refresh" || lazyLoad) {
          getRefresh(search.type === "search")({ keyword: search.value }, search.type === "refresh");
        } else {
          (_c = (_b = outRef.current) == null ? void 0 : _b.filterTreeNode) == null ? void 0 : _c.call(_b, search.value);
        }
      }
    }, [search, lazyLoad]);
    const onLazyLoad = lazyLoad ? async (parentNode, keyRef) => {
      const { dataLoad: dataLoad2, request: request2, convertNode: convertNode2, params: params2 } = props;
      const transformData = dataLoad2 || ((n) => n);
      try {
        let requestParams = params2;
        if (import_util.iup.isFunction(params2)) {
          requestParams = await params2(parentNode);
        }
        const extraParams = { lazyLoad: true, keyRef };
        const nodes = await request2({ parentNode, ...requestParams });
        parentNode.children = transformData(
          formatTreeNodes(parentNode, nodes, convertNode2, extraParams, parentNode.depth.level + 1),
          extraParams
        );
        return parentNode.children;
      } catch (e) {
        console.log(e);
        return [];
      }
    } : null;
    const defaultFilter = /* @__PURE__ */ import_react.default.createElement(import_util.Layout, { direction: "row", style: { padding: 5, alignItems: "center" } }, /* @__PURE__ */ import_react.default.createElement(
      import_baseComponent.Input,
      {
        value: search.value,
        onChange: (value) => {
          var _a;
          return setSearch({ type: "search", value: ((_a = value == null ? void 0 : value.trim) == null ? void 0 : _a.call(value)) || "" });
        },
        allowClear: true,
        suffix: search.value ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null) : /* @__PURE__ */ import_react.default.createElement(import_icons.SearchOutlined, { style: { opacity: 0.45 } })
      }
    ));
    const filterNode = import_util.iup.isFunction(showFilter) ? showFilter(defaultFilter) : showFilter ? defaultFilter : null;
    return /* @__PURE__ */ import_react.default.createElement(import_util.Layout, { style: { backgroundColor: import_util.cssVar.componentColor, ...style } }, filterNode, /* @__PURE__ */ import_react.default.createElement(import_util.Layout.Flex, { style: { position: "relative", overflow: "hidden" } }, /* @__PURE__ */ import_react.default.createElement(import_react.default.Suspense, { fallback: /* @__PURE__ */ import_react.default.createElement(import_tree.TreeLoading, null) }, /* @__PURE__ */ import_react.default.createElement(
      TreeRender,
      {
        ...others,
        virtual: virtual ?? lazyLoad,
        reader: dataReader,
        treeLoad: treeLoadCallback,
        lazyLoad: onLazyLoad
      }
    ))));
  },
  "AsyncTree"
);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AsyncTree
});
